//创建蛇类
class Snake{
    //创建蛇头
    head: HTMLElement;
    //创建蛇的身体
    bodies: HTMLCollection;
    //蛇的容器
    element: HTMLElement;
    constructor() {
        this.element = document.getElementById('snake')!;
        this.head = document.querySelector('#snake>div')!;
        this.bodies = this.element.getElementsByTagName('div');

    }
    //获取蛇头的坐标
    get X() {
        return this.head.offsetLeft;
    }
    get Y() {
        return this.head.offsetTop;
    }

    //设置蛇头的坐标
    set X(value: number) {
        //如果新值和旧值相同，则不修改，否则会一直修改
        if (this.head.offsetLeft == value) {
            return
        }
        //左右禁止掉头(第二节不能和第一节坐标重复)
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft===value) {
            // console.log('水平掉头了');
            if (value > this.X) {
                //新值大于旧值，此时蛇在向右移动，若发生掉头，则继续像原方向移动
                value = this.X -10
            } else {
                value = this.X + 10
            }
        }
        if (value < 0 || value > 290) {
            //抛出异常
            throw new Error('蛇撞墙了')
        }
        //移动身体
        this.moveBody()
        this.head.style.left = value + 'px'
        //此处获取最新蛇头坐标
        this.checkRepeat()
    }
    set Y(value: number) {
         //如果新值和旧值相同，则不修改，否则会一直修改
         if (this.head.offsetTop == value) {
            return
        }
         //上下禁止掉头(第二节不能和第一节坐标重复)
         if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop===value) {
            if (value > this.Y) {
                //新值大于旧值，此时蛇在向下移动，若发生掉头，则继续像原方向移动
                value = this.Y -10
            } else {
                value = this.Y + 10
            }
        }
        if (value < 0 || value > 290) {
            throw new Error('蛇撞墙了,游戏结束！')
        }
        //移动身体
        this.moveBody()
        this.head.style.top = value + 'px'
        //此处获取最新蛇头坐标
        this.checkRepeat()
    }
    //增加身体长度的方法
    addbodies() {
        //向容器最后添加一个div
        this.element.insertAdjacentHTML("beforeend","<div></div>")
    }
    //蛇身体移动的方法
    moveBody() {
        //从后往前移动，每一节等于前一节的位置坐标
        for (let i = this.bodies.length - 1; i > 0; i--){
            let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.left = X + 'px';
            (this.bodies[i] as HTMLElement).style.top = Y + 'px';
        }
    }
    //检查蛇头与身体某一节坐标是否重复
    checkRepeat() {
        for (let i = 1; i < this.bodies.length; i++){
            if ((this.X === (this.bodies[i] as HTMLElement).offsetLeft && this.Y === (this.bodies[i] as HTMLElement).offsetTop)) {
                throw new Error("撞到自己了，游戏结束！");
            }
        }
    }
}
export default Snake;